<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>requestIdleCallback</title>
</head>

<body>
  <script>
    function sleep(duration) {
      for (var t = Date.now(); Date.now() - t <= duration;) { }
    }
    const fibers = [
      () => {
        console.log('第1个任务开始');
        sleep(5000);
        console.log('第1个任务结束');
      },
      () => {
        console.log('第2个任务开始');
        sleep(20);
        console.log('第2个任务结束');
      },
      () => {
        console.log('第3个任务开始');
        sleep(20);
        console.log('第3个任务结束');
      }
    ]
    requestIdleCallback(workLoop);
    function workLoop(deadline) {
      //因为一帧是16.6ms,浏览器执行完高优先级之后，如果还有时间，会执行workLoop,timeRemaining获取此帧剩下的时间
      console.log(`本帧的剩余时间是`, deadline.timeRemaining());
      //如果没有剩余时间了，就会跳出循环
      while (deadline.timeRemaining() > 1 && works.length > 0) {
        performUnitOfWork();
      }
      //如果还有剩余任务
      if (works.length > 0) {
        console.log(`只剩下${deadline.timeRemaining()}ms，不够了，等待浏览器下次空闲 的时候再帮我调用`,);
        requestIdleCallback(workLoop);
      }
    }
    function performUnitOfWork() {
      let work = works.shift();//取出任务数组中的第一个任务,并移除第一个任务
      work();
    }
  </script>
</body>

</html>